package com.ztgf.order.api.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.WebUtils;
import com.ztgf.shopping.models.constant.ShoppingConstant;
import com.ztgf.sys.models.dto.SysDictDTO;
import com.ztgf.sys.models.service.ISysDictService;
import com.ztgf.sys.models.service.ISysMenuService;
import com.ztgf.user.models.dto.UserInfoDTO;
import com.ztgf.user.models.service.IUserLoginService;
import com.ztgf.user.models.service.IUserRoleRelationService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @author YUE
 * @create 2020-08-25 15:53
 */
@Slf4j
@Configuration
public class AuthInterceptor implements HandlerInterceptor {

    @DubboReference
    private IUserLoginService userLoginService;

    @DubboReference
    private ISysDictService sysDictService;

    @DubboReference
    private IUserRoleRelationService userRoleRelationService;

    @DubboReference
    private ISysMenuService sysMenuService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionId = CommonParameter.getHeadParamsBO().getSessionId();
        //判断是不是主账号（主账号拥有所有权限）
        UserInfoDTO userInfoDTO = userLoginService.getUserBySessionId(sessionId);
        if(null == userInfoDTO){
            return true;
        }
        if(userInfoDTO.getType() == 0){//主账号
            return true;
        } else{//子账号
            String shopManageStr = "/shopping-client/api/templetInfo/issueShopTemplate";//店铺装修接口

            String buyShopStr = "/order-client/api/orderInfo/placeOrder";//下单

            String orderPayStr = "/order-client/api/orderInfo/orderPay";//支付

            String commodityPushOrPoll = "/commodity-client/api/commodityInfo/updateStatus";//商品上下架
            String commoditySave = "/commodity-client/api/commodityInfo/saveReleaseCommodity";//商品发布

            String requestUrl = request.getRequestURI();
            if(requestUrl.equals(buyShopStr)){//购买
                StringBuffer stringBuffer = new StringBuffer();
                SysDictDTO sysDictDTO = sysDictService.getByName(ShoppingConstant.BUY_COMMODITY_AUTH_NAME);
                String value = sysDictDTO.getValue();//店铺管理权限id
                //这个用户是否有这个权限
                List<Long> roleIdList = userRoleRelationService.getRoleIdListByUserId(userInfoDTO.getId());//用户所有的权限id集合
                for (Long rolId : roleIdList) {
                    if(null == rolId){
                        continue;
                    }
                    List<Long> menuIdList = sysMenuService.selectMenuIdListByRoleId(rolId);//权限id
                    for (Long aLong : menuIdList) {
                        stringBuffer.append(aLong + ",");
                    }
                }
                List<String> allMenuId = Arrays.asList(stringBuffer.toString().split(","));
                if(allMenuId.contains(value)){//如果包含 就通过
                    return true;
                }
                Result result = new Result(CodeEnum.BUY_COMMODITY_AUTH_NAME);
                WebUtils.outPrint(response, JSON.toJSONString(result));
                return false;
            }
            if(requestUrl.equals(orderPayStr)){//支付
                StringBuffer stringBuffer = new StringBuffer();
                SysDictDTO sysDictDTO = sysDictService.getByName(ShoppingConstant.ORDER_PAY_AUTH_NAME);
                String value = sysDictDTO.getValue();//店铺管理权限id
                //这个用户是否有这个权限
                List<Long> roleIdList = userRoleRelationService.getRoleIdListByUserId(userInfoDTO.getId());//用户所有的权限id集合
                for (Long rolId : roleIdList) {
                    if(null == rolId){
                        continue;
                    }
                    List<Long> menuIdList = sysMenuService.selectMenuIdListByRoleId(rolId);//权限id
                    for (Long aLong : menuIdList) {
                        stringBuffer.append(aLong + ",");
                    }
                }
                List<String> allMenuId = Arrays.asList(stringBuffer.toString().split(","));
                if(allMenuId.contains(value)){//如果包含 就通过
                    return true;
                }
                Result result = new Result(CodeEnum.ORDER_PAY_AUTH_NAME);
                WebUtils.outPrint(response, JSON.toJSONString(result));
                return false;
            }
            return true;
        }
    }
}
